package phoneregistration.controller.converter.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import phoneregistration.controller.converter.PhoneConverter;
import phoneregistration.controller.model.PhoneModel;
import phoneregistration.domain.Phone;
import phoneregistration.service.CompanyService;
import phoneregistration.service.UserService;

@Service
public class PhoneConverterImpl implements PhoneConverter {

    private CompanyService companyService;
    private UserService userService;

    @Autowired
    public PhoneConverterImpl(CompanyService companyService, UserService userService) {
        this.companyService = companyService;
        this.userService = userService;
    }

    public PhoneModel convertEntityToModel(Phone e) {
        assertEntity(e);
        
        PhoneModel model = new PhoneModel();
        
        model.setNumber(e.getNumber());
        model.setCompanyId(e.getCompany().getId());
        model.setUserId(e.getUser().getId()+"");
        
        return model;
    }

    private void assertEntity(Phone e) {
        Assert.notNull(e);
        Assert.notNull(e.getNumber());
        Assert.notNull(e.getCompany());
        Assert.notNull(e.getUser());
        Assert.notNull(e.getCompany().getId());
        Assert.notNull(e.getUser().getId());
    }
    public Phone convertModelToEntity(PhoneModel e) {
        assertModel(e);
        
        Phone entity = new Phone();
        entity.setNumber(e.getNumber());
        entity.setCompany(companyService.findOne(e.getCompanyId()));
        entity.setUser(userService.findOne(Long.parseLong(e.getUserId())));
        
        return entity;
    }

    private void assertModel(PhoneModel e) {
        Assert.notNull(e);
        Assert.notNull(e.getNumber());
        Assert.notNull(e.getCompanyId());
        Assert.notNull(e.getUserId());
    }

}
